package com.dao.impl;

import com.dao.BookDao;
import com.entity.Book;
import com.entity.Page;
import com.util.DbUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

public class BookDaoImpl implements BookDao {
    private QueryRunner runner = new QueryRunner(DbUtil.getDds());
    @Override
    public List<Book> selectAll() {
        String sql = "select * from book";
        try {
            return runner.query(sql,new BeanListHandler<>(Book.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int selectAllByPageCount() {
        String sql = "select count(*) from book;";
        try {
            long count = runner.query(sql, new ScalarHandler<Long>());
            return (int)count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int addOne(Book book) {
        String sql = "insert into book values(null,?,?,?,?,?)";
        try {
            return runner.update(sql,book.getName(),book.getPrice(),book.getAuthor(),book.getPublisher(),book.getDescription());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int deleteOne(String bookId) {
        String sql = "delete from book where id = ?";
        try {
            return runner.update(sql, bookId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Book selectOne(String bookId) {
        String sql = "select * from book where id = ?";
        try {
            return runner.query(sql, new BeanHandler<Book>(Book.class), bookId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Book> selectAllByPage(Page page) {
        String sql = "select * from book limit ?, ?;";
        try {
            List<Book> list = runner.query(sql, new BeanListHandler<Book>(Book.class), page.getStartRows(),
                    page.getPageSize());
            return  list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    public int updateOne(Book book) {
        String sql = "update book set name=? , author=? ,publisher=?, description=?, price=? where id = ?";
        try {
            return runner.update(sql, book.getName(),book.getAuthor(),book.getPublisher(),book.getDescription(),book.getPrice(),book.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
